package git.soulbgm.common.pojo;

import git.soulbgm.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * @author SoulBGM
 * @version 1.0
 * @date 2019/7/4 17:21
 */
@Slf4j
public abstract class BaseModelCallback<T> extends BaseCallback {

    private Class<T> clazz;

    public BaseModelCallback() {
        Type type = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = null;
        if (type instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) type;
        }
        if (parameterizedType == null) {
            this.clazz = (Class<T>) Object.class;
        } else {
            try {
                this.clazz = (Class<T>) Class.forName(parameterizedType.getActualTypeArguments()[0].getTypeName());
            } catch (ClassNotFoundException e) {
                log.error("Class.forName获得Class对象异常", e);
            }
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        ResponseBody body = response.body();
        byte[] bytes = body != null ? body.bytes() : new byte[0];
        String json = new String(bytes);
        if (clazz == Map.class || clazz == HashMap.class) {
            onResponse(call, (T) JsonUtil.parse(json));
        } else {
            onResponse(call, JsonUtil.parse(json, clazz));
        }
    }

    /**
     * 在远程服务器成功返回HTTP响应时调用
     *
     * @param call  Call对象
     * @param model 反序列化之后的实体
     */
    public abstract void onResponse(Call call, T model);
}
